﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WFExtended.Twitter
{
    internal static class MultipartFormData
    {
        internal const string _BOUNDARY = "--------------------r4nd0m";

        internal static Stream GetMultipartFormData(Dictionary<string, object> parameters)
        {
            Stream formDataStream = new MemoryStream();
            Encoding encoding = Encoding.UTF8;

            foreach (KeyValuePair<string, object> kvp in parameters)
            {
                if (kvp.Value.GetType() == typeof(Media))
                {	//assume this to be a byte stream
                    Media media = (Media)kvp.Value;

                    string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: application/octet-stream\r\n\r\n",
                        _BOUNDARY,
                        kvp.Key,
                        (!String.IsNullOrEmpty(media.Filename)) ? media.Filename : "media");

                    byte[] headerBytes = encoding.GetBytes(header);

                    formDataStream.Write(headerBytes, 0, headerBytes.Length);
                    formDataStream.Write(media.Content, 0, media.Content.Length);
                }
                else
                {	//this is normal text data
                    string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
                        _BOUNDARY,
                        kvp.Key,
                        kvp.Value);

                    byte[] headerBytes = encoding.GetBytes(header);

                    formDataStream.Write(headerBytes, 0, headerBytes.Length);
                }
            }

            string footer = string.Format("\r\n--{0}--\r\n", _BOUNDARY);
            formDataStream.Write(encoding.GetBytes(footer), 0, footer.Length);
            formDataStream.Position = 0;
            byte[] returndata = new byte[formDataStream.Length];

            formDataStream.Read(returndata, 0, returndata.Length);
            formDataStream.Close();

            return new MemoryStream(returndata);
        }
    }
}
